const express = require("express");
const router = express.Router();
const db = require("../sql");
const { generateToken } = require("../utils/jwt");

// 登录路由
router.post("/admin-login", async (req, res) => {
  const { userName, password } = req.body;
  if (!userName || !password) {
    return res.json({
      success: false,
      data: "Username and password are required.",
      message: "Username and password are required.",
    });
  }

  try {
    const sql = "SELECT id, password FROM adminUsers WHERE userName = ?";
    const result = await db.query(sql, [userName]);

    if (result.length === 0) {
      return res.json({ success: false, message: "用户名错误" });
    }

    if (password == result[0].password) {
      res.json({
        success: true,
        data: {
          id: result[0].id,
          userName,
          token: generateToken(userName),
        },
      });
    } else {
      res.json({ success: false, message: "密码错误" });
    }
  } catch (error) {
    res.json({ success: false, data: error.message });
  }
});

// 修改密码路由
router.post("/change-password", async (req, res) => {
  const { userName, oldPassword, newPassword, id } = req.body;
  //   if (!userName || !oldPassword || !newPassword) {
  //     return res.json({ success: false, message: "All fields are required." });
  //   }

  try {
    // const userSql = "SELECT id, password FROM adminUsers WHERE userName = ?";
    // const userResult = await db.query(userSql, [userName]);

    // if (userResult.length === 0) {
    //   return res.json({ success: false, message: "没找到用户" });
    // }

    // if (oldPassword != userResult[0].password) {
    //   return res.json({ success: false, message: "旧密码错误" });
    // }

    const updateSql = "UPDATE adminUsers SET password = ? WHERE id = ?";
    await db.query(updateSql, [newPassword, id]);

    res.json({ success: true, message: "Password updated successfully." });
  } catch (error) {
    res.json({ success: false, message: error.message });
  }
});

module.exports = router;
